package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //一个servlet处理不同请求情况
        //前端发起查询博客列表请求，查询数据库，以json格式返回响应
        String respJson;
        BlogDao blogDao = new BlogDao();
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            //请求中没有query string，说明请求来自博客列表页
            List<Blog> blogList = blogDao.getBlogs();//查所有
            respJson = objectMapper.writeValueAsString(blogList);
        } else {
            //请求中有query string，说明请求来自博客详情页
            Blog blog = blogDao.getBlog(Integer.parseInt(blogId));//查指定
            respJson = objectMapper.writeValueAsString(blog);
        }
        System.out.println("respJson: " + respJson);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || title.length() == 0 || content == null || content.length() == 0) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("标题或正文为空");
            return;
        }

        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录：session为空");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录：user为空");
            return;
        }

        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());

        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);

        resp.sendRedirect("blog_list.html");
    }
}
